package com.zxl.working.utils;

import com.zxl.working.mapper.backend.SellerMapper;
import com.zxl.working.mapper.backend.ServiceMapper;
import com.zxl.working.service.impl.SellerServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SerialNoUtil {
    @Resource
    private ServiceMapper serviceMapper;
    @Resource
    private SellerMapper sellerMapper;
    /**
     * 根据类别、平台生成流水号
     * 格式为 类别+平台+日期+顺序号(共19位)
     * @param type
     * @param platform
     * @return
     */
    public String genSerialNo(String type, String platform, String merchant){
        if(platform==null || platform.equals("")){
            platform="A";//默认平台为A
        }
        if(merchant.length()==1){
            merchant="0000"+merchant;
        }else if(merchant.length()==2){
            merchant="000"+merchant;
        }else if(merchant.length()==3){
            merchant="00"+merchant;
        }else if(merchant.length()==4){
            merchant="0"+merchant;
        }
        String rules = type + platform + merchant + getCurrentDate();
        String lastOrder = "";
        //发票订单在seller_bill
        if(type.equals("P")) {
            lastOrder = serviceMapper.qryLastOrderId(rules + "%");
        }
        //费用订单在seller_provide_order
        if(type.equals("F")) {
            lastOrder = sellerMapper.qryLastOrderIdInF(rules + "%");
        }

        //流水订单在provide_detail
        if(type.equals("Q")) {
            lastOrder = sellerMapper.qryLastOrderIdInL(rules + "%");
        }

        //上传充值记录在seller_upload_detail
        if(type.equals("C")) {
            lastOrder = sellerMapper.qryLastOrderIdInC(rules + "%");
        }
        //LA00001202010270001
        String serialNo = "";
        String before = "";
        String after = "";
        String _serial = "";


        if(lastOrder != null && !lastOrder.equals("")) {
            String temp = lastOrder.substring(14,15);
            //如果数据库中该商户当日已经存在订单，计算新的订单号
            if (temp.equals("0")) {
                //如果最后一位是0则往前多截取一位
                _serial = lastOrder.substring(13);
                before = lastOrder.substring(0, 13);
            } else {
                //截取天数最后一位
                _serial = lastOrder.substring(14);
                before = lastOrder.substring(0, 14);
            }

            int serial = Integer.parseInt(_serial) + 1;

            serialNo = before + serial;
        }else{
            //如果数据库中不存在，直接以0001开始
            serialNo = rules + "0001";
        }
        return serialNo;
    }

    public String getCurrentDate(){
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }


}
